
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>点击劫持保护 &#8212; Django 3.2.6.dev 文档</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="next" title="contrib 包" href="contrib/index.html" />
    <link rel="prev" title="基于类的通用视图——扁平化索引" href="class-based-views/flattened-index.html" />



 
<script src="../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 3.2.6.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="class-based-views/flattened-index.html" title="基于类的通用视图——扁平化索引">previous</a>
     |
    <a href="index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="contrib/index.html" title="&lt;code class=&#34;docutils literal notranslate&#34;&gt;&lt;span class=&#34;pre&#34;&gt;contrib&lt;/span&gt;&lt;/code&gt; 包">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="ref-clickjacking">
            
  <div class="section" id="s-module-django.middleware.clickjacking">
<span id="s-clickjacking-protection"></span><span id="module-django.middleware.clickjacking"></span><span id="clickjacking-protection"></span><h1>点击劫持保护<a class="headerlink" href="#module-django.middleware.clickjacking" title="永久链接至标题">¶</a></h1>
<p>点击劫持中间件和装饰器提供易于使用的保护，以防止 <a class="reference external" href="https://en.wikipedia.org/wiki/Clickjacking">点击劫持</a> 。 当恶意网站欺骗用户点击另一个网站的隐藏元素时，就会发生这种类型的攻击，该元素已被加载到一个隐藏的框架或 iframe 中。</p>
<div class="section" id="s-an-example-of-clickjacking">
<span id="an-example-of-clickjacking"></span><h2>点击劫持的一个例子<a class="headerlink" href="#an-example-of-clickjacking" title="永久链接至标题">¶</a></h2>
<p>假设一家在线商店有一个页面，登录的用户可以点击“立即购买”来购买商品。用户为了方便，选择了保持登录商店。攻击者网站可能会在自己的一个页面上创建一个“I Like Ponies”按钮，并在一个透明的 iframe 中加载商店的页面，使“立即购买”按钮无形中覆盖在“I Like Ponies”按钮上。如果用户访问攻击者的网站，点击“I Like Ponies”将导致无意中点击“立即购买”按钮，并在不知情的情况下购买该商品。</p>
</div>
<div class="section" id="s-preventing-clickjacking">
<span id="s-clickjacking-prevention"></span><span id="preventing-clickjacking"></span><span id="clickjacking-prevention"></span><h2>防止点击劫持<a class="headerlink" href="#preventing-clickjacking" title="永久链接至标题">¶</a></h2>
<p>现代浏览器尊重 <a class="reference external" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options">X-Frame-Options</a> HTTP 头，它表明是否允许在框架或 iframe 中加载资源。如果响应包含值为 <code class="docutils literal notranslate"><span class="pre">SAMEORIGIN</span></code> 的头，那么只有当请求来自同一个网站时，浏览器才会在框架中加载资源。如果头被设置为 <code class="docutils literal notranslate"><span class="pre">DENY</span></code>，那么无论请求是由哪个网站发出的，浏览器都会阻止资源在框架中加载。</p>
<p>Django 提供了一些方法来在你的网站的响应中包含这个头：</p>
<ol class="arabic simple">
<li>一个在所有响应中设置头的中间件。</li>
<li>一组可用于覆盖中间件或仅为某些视图设置头的视图装饰器。</li>
</ol>
<p><code class="docutils literal notranslate"><span class="pre">X-Frame-Options</span></code> HTTP 头只有在响应中还没有出现的情况下，才会被中间件或视图装饰者设置。</p>
</div>
<div class="section" id="s-how-to-use-it">
<span id="how-to-use-it"></span><h2>如何使用它<a class="headerlink" href="#how-to-use-it" title="永久链接至标题">¶</a></h2>
<div class="section" id="s-setting-x-frame-options-for-all-responses">
<span id="setting-x-frame-options-for-all-responses"></span><h3>为所有响应设置 <code class="docutils literal notranslate"><span class="pre">X-Frame-Options</span></code><a class="headerlink" href="#setting-x-frame-options-for-all-responses" title="永久链接至标题">¶</a></h3>
<p>要为你的网站的所有响应设置相同的 <code class="docutils literal notranslate"><span class="pre">X-FrameOptions</span></code> 值，把 <code class="docutils literal notranslate"><span class="pre">'django.middleware.clickjacking.XFrameOptionsMiddleware'</span></code> 放到 <a class="reference internal" href="settings.html#std:setting-MIDDLEWARE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MIDDLEWARE</span></code></a>：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">MIDDLEWARE</span> <span class="o">=</span> <span class="p">[</span>
    <span class="o">...</span>
    <span class="s1">&#39;django.middleware.clickjacking.XFrameOptionsMiddleware&#39;</span><span class="p">,</span>
    <span class="o">...</span>
<span class="p">]</span>
</pre></div>
</div>
<p>这个中间件在 <a class="reference internal" href="django-admin.html#django-admin-startproject"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">startproject</span></code></a> 生成的配置文件中启用了。</p>
<p>默认情况下，中间件将为每个传出的 <code class="docutils literal notranslate"><span class="pre">HttpResponse</span></code> 设置 <code class="docutils literal notranslate"><span class="pre">X-</span> <span class="pre">Frame-Options</span></code> 头为 <code class="docutils literal notranslate"><span class="pre">DENY</span></code>。如果你想为这个头设置任何其他的值，可以设置 <a class="reference internal" href="settings.html#std:setting-X_FRAME_OPTIONS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">X_FRAME_OPTIONS</span></code></a> 配置：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">X_FRAME_OPTIONS</span> <span class="o">=</span> <span class="s1">&#39;SAMEORIGIN&#39;</span>
</pre></div>
</div>
<p>在使用中间件时，有些视图可能 <strong>不希望</strong> 设置 <code class="docutils literal notranslate"><span class="pre">X-</span> <span class="pre">Frame-Options</span></code> 头。对于这些情况，你可以使用一个视图装饰器，告诉中间件不要设置头：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.http</span> <span class="kn">import</span> <span class="n">HttpResponse</span>
<span class="kn">from</span> <span class="nn">django.views.decorators.clickjacking</span> <span class="kn">import</span> <span class="n">xframe_options_exempt</span>

<span class="nd">@xframe_options_exempt</span>
<span class="k">def</span> <span class="nf">ok_to_load_in_a_frame</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s2">&quot;This page is safe to load in a frame on any site.&quot;</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">如果你想在框架或 iframe 中提交表单或访问会话 cookie，你可能需要修改 <a class="reference internal" href="settings.html#std:setting-CSRF_COOKIE_SAMESITE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CSRF_COOKIE_SAMESITE</span></code></a> 或 <a class="reference internal" href="settings.html#std:setting-SESSION_COOKIE_SAMESITE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">SESSION_COOKIE_SAMESITE</span></code></a> 配置。</p>
</div>
</div>
<div class="section" id="s-setting-x-frame-options-per-view">
<span id="setting-x-frame-options-per-view"></span><h3>为每个视图设置 <code class="docutils literal notranslate"><span class="pre">X-Frame-Options</span></code>。<a class="headerlink" href="#setting-x-frame-options-per-view" title="永久链接至标题">¶</a></h3>
<p>要在每个视图上设置 <code class="docutils literal notranslate"><span class="pre">X-Frame-Options</span></code> 头，Django 提供了这些装饰器：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.http</span> <span class="kn">import</span> <span class="n">HttpResponse</span>
<span class="kn">from</span> <span class="nn">django.views.decorators.clickjacking</span> <span class="kn">import</span> <span class="n">xframe_options_deny</span>
<span class="kn">from</span> <span class="nn">django.views.decorators.clickjacking</span> <span class="kn">import</span> <span class="n">xframe_options_sameorigin</span>

<span class="nd">@xframe_options_deny</span>
<span class="k">def</span> <span class="nf">view_one</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s2">&quot;I won&#39;t display in any frame!&quot;</span><span class="p">)</span>

<span class="nd">@xframe_options_sameorigin</span>
<span class="k">def</span> <span class="nf">view_two</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">HttpResponse</span><span class="p">(</span><span class="s2">&quot;Display in a frame if it&#39;s from the same origin as me.&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>请注意，你可以将装饰器与中间件一起使用。使用装饰器可以覆盖中间件。</p>
</div>
</div>
<div class="section" id="s-limitations">
<span id="limitations"></span><h2>限制<a class="headerlink" href="#limitations" title="永久链接至标题">¶</a></h2>
<p><code class="docutils literal notranslate"><span class="pre">X-Frame-Options</span></code> 头只能在现代浏览器中防止点击劫持。旧的浏览器会悄悄地忽略这个头，需要 <a class="reference external" href="https://en.wikipedia.org/wiki/Clickjacking#Prevention">其他的防止点击劫持技术</a> 。</p>
<div class="section" id="s-browsers-that-support-x-frame-options">
<span id="browsers-that-support-x-frame-options"></span><h3>支持 <code class="docutils literal notranslate"><span class="pre">X-Frame-Options</span></code> 的浏览器。<a class="headerlink" href="#browsers-that-support-x-frame-options" title="永久链接至标题">¶</a></h3>
<ul class="simple">
<li>Internet Explorer 8+</li>
<li>Edge</li>
<li>Firefox 3.6.9+</li>
<li>Opera 10.5+</li>
<li>Safari 4+</li>
<li>Chrome 4.1+</li>
</ul>
</div>
<div class="section" id="s-see-also">
<span id="see-also"></span><h3>另见<a class="headerlink" href="#see-also" title="永久链接至标题">¶</a></h3>
<p>支持 <code class="docutils literal notranslate"><span class="pre">X-Frame-Options</span></code> 的浏览器的 <a class="reference external" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options#browser_compatibility">完整列表</a> 。</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">点击劫持保护</a><ul>
<li><a class="reference internal" href="#an-example-of-clickjacking">点击劫持的一个例子</a></li>
<li><a class="reference internal" href="#preventing-clickjacking">防止点击劫持</a></li>
<li><a class="reference internal" href="#how-to-use-it">如何使用它</a><ul>
<li><a class="reference internal" href="#setting-x-frame-options-for-all-responses">为所有响应设置 <code class="docutils literal notranslate"><span class="pre">X-Frame-Options</span></code></a></li>
<li><a class="reference internal" href="#setting-x-frame-options-per-view">为每个视图设置 <code class="docutils literal notranslate"><span class="pre">X-Frame-Options</span></code>。</a></li>
</ul>
</li>
<li><a class="reference internal" href="#limitations">限制</a><ul>
<li><a class="reference internal" href="#browsers-that-support-x-frame-options">支持 <code class="docutils literal notranslate"><span class="pre">X-Frame-Options</span></code> 的浏览器。</a></li>
<li><a class="reference internal" href="#see-also">另见</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="class-based-views/flattened-index.html"
                        title="上一章">基于类的通用视图——扁平化索引</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="contrib/index.html"
                        title="下一章"><code class="docutils literal notranslate"><span class="pre">contrib</span></code> 包</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/ref/clickjacking.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">7月 23, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="class-based-views/flattened-index.html" title="基于类的通用视图——扁平化索引">previous</a>
     |
    <a href="index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="contrib/index.html" title="&lt;code class=&#34;docutils literal notranslate&#34;&gt;&lt;span class=&#34;pre&#34;&gt;contrib&lt;/span&gt;&lt;/code&gt; 包">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>